<template>
  <div>
    <el-dialog v-model="integralState" :title="`${modelData.title}积分`" width="500px" :before-close="cancel">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
    <el-form-item :label="`${modelData.title}积分`" prop="amount">
      <el-input-number v-model="ruleForm.amount" :min="1" controls-position="right" :placeholder="`请填写${modelData.title}积分`" />
    </el-form-item>
    <el-form-item :label="`${modelData.title}原因`">
      <el-input v-model="ruleForm.remark" clearable :placeholder="`请填写${modelData.title}原因`" />
    </el-form-item>
    
  </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="formValidate(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import integralApi from "@/api/integralApi.js";
import type { FormInstance, FormRules } from 'element-plus'
const props = defineProps({
  integralState: Boolean,
  modelData: {
    required: true,
    type: Object,
    defautl: {},
  },
});
const { modelData } = toRefs(props)
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  amount: 1,
  remark: '',
  type: '',
  userId: '',
})

const rules = reactive<FormRules>({
  amount: [
    { required: true, message: '请填写积分数量', trigger: ['blur','change']},
  ],

})

const formValidate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      submitForm()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const submitForm = async()=> {
  ruleForm.type = modelData?.value.type
  ruleForm.userId = modelData?.value.userId
  let rs = await integralApi.updateIntegral(ruleForm)
  if(rs.code === 200) {
    ElMessage({
      type: "success",
      message:`${modelData?.value.title}积分成功`,
    });
    setTimeout(() => {
      ruleFormRef.value.resetFields()
    }, 0);
    confirm()
  }
  
}

const confirm = () => {
  emit("confirm");
  cancel()
};

const cancel = () => {
  ruleForm.amount = 1
  ruleForm.remark = ''
  emit("cancel");
}
const emit = defineEmits(["confirm", "cancel"]);
</script>

<style lang="scss" scoped>
:deep(.el-input-number) {
  width: 100%;
}
.el-form {
  padding-right: 80px;
}
</style>